import {forwardRef, ForwardRefRenderFunction, useImperativeHandle, useMemo, Children} from "react";
import {Form as AntdForm} from 'antd';
import {CommonComponentProps} from "../../../../components/editor/interface.ts";
import dayjs from 'dayjs';

export interface FormRef {
    submit: () => void
}


const FormProd: ForwardRefRenderFunction<FormRef, CommonComponentProps> = ({children,layout,name, onFinish}, ref) => {
    const [form] = AntdForm.useForm();
    useImperativeHandle(ref, () => {
        return {
            submit:async () => {
                form.submit();

            }
        }
    }, [form]);

    const formItems = useMemo(() => {
        return Children.map(children, (item: any) => {
            return {
                label: item.props?.label,
                name: item.props?.name,
                type: item.props?.type,
                id: item.props?.id,
                rules: item.props?.rules,
                prod:item
            }
        });
    }, [children]);

    async function save(values: any) {
        console.log(await form.getFieldsValue())
        Object.keys(values).forEach(key => {
            if (dayjs.isDayjs(values[key])) {
                values[key] = values[key].format('YYYY-MM-DD')
            }
        })
        onFinish(values);
    }

    return (<AntdForm layout={layout} name={name} labelCol={{span: 5}} wrapperCol={{span: 18}} form={form} onFinish={save} >
            {formItems.map((item: any) => {
                return (
                    <div
                        key={item.id}
                    >
                        {item.prod}
                    </div>
                )
            })}
        </AntdForm>

    )

}


export default forwardRef(FormProd);